use std::sync::Mutex;
use multi_platform_crawler_lib::*;

// 测试应用状态初始化
#[tokio::test]
async fn test_app_state_initialization() {
    let temp_dir = tempfile::tempdir().unwrap();
    let data_dir = temp_dir.path().to_path_buf();
    
    let app_state = state::AppState::new(data_dir.clone()).unwrap();
    
    // 检查数据目录是否创建
    assert!(data_dir.exists());
    
    // 检查数据库是否初始化
    let health_check = app_state.database.health_check().unwrap();
    assert!(health_check);
}

// 测试数据库迁移
#[tokio::test]
async fn test_database_migrations() {
    let temp_dir = tempfile::tempdir().unwrap();
    let db_path = temp_dir.path().join("test.db");
    
    let db = database::DatabaseConnection::new(&db_path, database::DatabaseConfig::default()).unwrap();
    let conn = db.get_connection();
    let conn = conn.lock().unwrap();
    
    let migration_manager = database::MigrationManager::new();
    migration_manager.migrate(&conn).unwrap();
    
    // 检查迁移表是否存在
    let table_exists: bool = conn.query_row(
        "SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='migrations'",
        [],
        |row| row.get::<_, i32>(0).map(|count| count > 0)
    ).unwrap();
    
    assert!(table_exists);
    
    // 检查当前版本
    let current_version = migration_manager.get_current_version(&conn).unwrap();
    assert!(current_version > 0);
}

// 测试配置管理
#[tokio::test]
async fn test_config_management() {
    let temp_dir = tempfile::tempdir().unwrap();
    let db_path = temp_dir.path().join("test.db");
    
    let db = database::DatabaseConnection::new(&db_path, database::DatabaseConfig::default()).unwrap();
    let conn = db.get_connection();
    let conn = conn.lock().unwrap();
    
    // 初始化数据库
    let migration_manager = database::MigrationManager::new();
    migration_manager.migrate(&conn).unwrap();
    
    // 测试默认配置
    let config = db.get_config().unwrap();
    assert!(config.is_some());
    
    let mut config = config.unwrap();
    config.theme = "dark".to_string();
    config.auto_start = true;
    
    // 保存配置
    db.save_config(&config).unwrap();
    
    // 读取配置
    let saved_config = db.get_config().unwrap().unwrap();
    assert_eq!(saved_config.theme, "dark");
    assert_eq!(saved_config.auto_start, true);
}

// 测试日志系统
#[tokio::test]
async fn test_logging_system() {
    let temp_dir = tempfile::tempdir().unwrap();
    let db_path = temp_dir.path().join("test.db");
    
    let db = database::DatabaseConnection::new(&db_path, database::DatabaseConfig::default()).unwrap();
    let conn = db.get_connection();
    let conn = conn.lock().unwrap();
    
    // 初始化数据库
    let migration_manager = database::MigrationManager::new();
    migration_manager.migrate(&conn).unwrap();
    
    // 添加日志条目
    let log_entry = database::LogEntry::new("info", "Test log message");
    db.add_log(&log_entry).unwrap();
    
    // 读取日志
    let logs = db.get_logs(Some(10), None).unwrap();
    assert_eq!(logs.len(), 1);
    assert_eq!(logs[0].message, "Test log message");
    assert_eq!(logs[0].level, "info");
    
    // 测试日志过滤
    let error_entry = database::LogEntry::new("error", "Test error message");
    db.add_log(&error_entry).unwrap();
    
    let error_logs = db.get_logs(None, Some("error")).unwrap();
    assert_eq!(error_logs.len(), 1);
    assert_eq!(error_logs[0].level, "error");
}

// 测试错误处理系统
#[tokio::test]
async fn test_error_handling() {
    use error::*;
    
    let temp_dir = tempfile::tempdir().unwrap();
    let db_path = temp_dir.path().join("test.db");
    let db = std::sync::Arc::new(
        database::DatabaseConnection::new(&db_path, database::DatabaseConfig::default()).unwrap()
    );
    
    let config = ErrorConfig::default();
    let error_handler = ErrorHandler::new(config, db);
    
    // 测试错误处理
    let app_error = AppError::database("Test database error");
    let context = ErrorContext::default();
    
    let recovery_result = error_handler.handle_error(app_error, Some(context), None).await.unwrap();
    
    // 检查恢复结果
    assert!(!recovery_result.success); // 数据库错误通常不可恢复
    
    // 测试可恢复错误
    let network_error = AppError::network("Test network error");
    let recovery_result = error_handler.handle_error(network_error, None, None).await.unwrap();
    
    // 网络错误应该尝试重试
    assert_eq!(recovery_result.attempts, 3); // 默认重试3次
}

// 测试命令处理
#[tokio::test]
async fn test_command_handlers() {
    let temp_dir = tempfile::tempdir().unwrap();
    let data_dir = temp_dir.path().to_path_buf();
    let app_state = Mutex::new(state::AppState::new(data_dir).unwrap());
    
    // 测试获取应用信息
    let app_info = commands::get_app_info(mock_app()).await.unwrap();
    assert!(!app_info.name.is_empty());
    assert!(!app_info.version.is_empty());
    
    // 测试获取系统信息
    let system_info = commands::get_system_info().await.unwrap();
    assert!(!system_info.platform.is_empty());
    assert!(!system_info.arch.is_empty());
    
    // 测试配置命令
    let config = commands::get_app_config(tauri::State::from(&app_state)).await.unwrap();
    assert!(!config.id.is_empty());
    
    // 测试设置配置
    let mut new_config = config.clone();
    new_config.theme = "dark".to_string();
    
    let result = commands::set_app_config(new_config, tauri::State::from(&app_state)).await.unwrap();
    assert!(result);
}

// 测试文件操作命令
#[tokio::test]
async fn test_file_operations() {
    let temp_dir = tempfile::tempdir().unwrap();
    let test_file = temp_dir.path().join("test.txt");
    let test_content = "Hello, Tauri!";
    
    // 测试写入文件
    let write_result = commands::write_text_file(
        test_file.to_string_lossy().to_string(),
        test_content.to_string()
    ).await.unwrap();
    assert!(write_result);
    
    // 测试文件是否存在
    let exists = commands::file_exists(test_file.to_string_lossy().to_string()).await.unwrap();
    assert!(exists);
    
    // 测试读取文件
    let read_content = commands::read_text_file(test_file.to_string_lossy().to_string()).await.unwrap();
    assert_eq!(read_content, test_content);
}

// 测试工具命令
#[tokio::test]
async fn test_utility_commands() {
    // 测试 UUID 生成
    let uuid1 = commands::generate_uuid().await.unwrap();
    let uuid2 = commands::generate_uuid().await.unwrap();
    
    assert_ne!(uuid1, uuid2);
    assert_eq!(uuid1.len(), 36); // UUID 标准长度
    
    // 测试时间戳生成
    let timestamp = commands::get_current_timestamp().await.unwrap();
    assert!(!timestamp.is_empty());
    
    // 验证时间戳格式
    let parsed_time = chrono::DateTime::parse_from_rfc3339(&timestamp);
    assert!(parsed_time.is_ok());
}

// 测试进程信息
#[tokio::test]
async fn test_process_info() {
    let process_info = commands::get_process_info().await.unwrap();
    
    // 检查返回的 JSON 结构
    assert!(process_info.get("pid").is_some());
    assert!(process_info.get("name").is_some());
    assert!(process_info.get("memory").is_some());
}

// 测试数据库性能
#[tokio::test]
async fn test_database_performance() {
    let temp_dir = tempfile::tempdir().unwrap();
    let db_path = temp_dir.path().join("perf_test.db");
    
    let db = database::DatabaseConnection::new(&db_path, database::DatabaseConfig::default()).unwrap();
    let conn = db.get_connection();
    let conn = conn.lock().unwrap();
    
    // 初始化数据库
    let migration_manager = database::MigrationManager::new();
    migration_manager.migrate(&conn).unwrap();
    
    let start_time = std::time::Instant::now();
    
    // 插入大量日志条目
    for i in 0..1000 {
        let log_entry = database::LogEntry::new("info", &format!("Test log message {}", i));
        db.add_log(&log_entry).unwrap();
    }
    
    let insert_duration = start_time.elapsed();
    println!("插入1000条日志耗时: {:?}", insert_duration);
    
    // 查询性能测试
    let query_start = std::time::Instant::now();
    let logs = db.get_logs(Some(100), None).unwrap();
    let query_duration = query_start.elapsed();
    
    println!("查询100条日志耗时: {:?}", query_duration);
    
    assert_eq!(logs.len(), 100);
    assert!(insert_duration.as_millis() < 1000); // 插入应该在1秒内完成
    assert!(query_duration.as_millis() < 100);   // 查询应该在100ms内完成
}

// 测试并发访问
#[tokio::test]
async fn test_concurrent_access() {
    let temp_dir = tempfile::tempdir().unwrap();
    let db_path = temp_dir.path().join("concurrent_test.db");
    
    let db = std::sync::Arc::new(
        database::DatabaseConnection::new(&db_path, database::DatabaseConfig::default()).unwrap()
    );
    
    let conn = db.get_connection();
    let conn = conn.lock().unwrap();
    
    // 初始化数据库
    let migration_manager = database::MigrationManager::new();
    migration_manager.migrate(&conn).unwrap();
    drop(conn);
    
    // 并发写入测试
    let mut handles = vec![];
    
    for i in 0..10 {
        let db_clone = db.clone();
        let handle = tokio::spawn(async move {
            for j in 0..100 {
                let log_entry = database::LogEntry::new("info", &format!("Thread {} message {}", i, j));
                db_clone.add_log(&log_entry).unwrap();
            }
        });
        handles.push(handle);
    }
    
    // 等待所有任务完成
    for handle in handles {
        handle.await.unwrap();
    }
    
    // 验证数据完整性
    let logs = db.get_logs(None, None).unwrap();
    assert_eq!(logs.len(), 1000); // 10个线程 × 100条消息
}

// 辅助函数：创建模拟应用
fn mock_app() -> tauri::AppHandle<MockRuntime> {
    let app = mock_app();
    app
}
